/**
 * kaCropper 封装
 * 
 * 版本：v1.0
 * 
 * Stanley
 **/
layui.define(['jquery'],
    function (exports) {
        var $ = layui.jquery, layer = layui.layer;
        var html = "<div class=\"layui-fluid showImgEdit\" style=\"display: none;\padding:15px;\">\n" +
            "    <div class=\"layui-form-item\">\n" +
            "        <div class=\"layui-input-inline layui-btn-container\" style=\"width: auto;\">\n" +
            "            <label for=\"cropper_avatarImgUpload\" class=\"layui-btn layui-btn-primary\">\n" +
            "                <i class=\"layui-icon\">&#xe67c;</i>选择图片\n" +
            "            </label>\n" +
            "            <input class=\"layui-upload-file\" id=\"cropper_avatarImgUpload\" type=\"file\" value=\"选择图片\" name=\"file\">\n" +
            "        </div>\n" +
            "        <div class=\"layui-form-mid layui-word-aux\">请上传图片进行头像截取，完成后保存修改即可</div>\n" +
            "    </div>\n" +
            "    <div class=\"layui-row layui-col-space15\">\n" +
            "        <div class=\"layui-col-xs9\" style=\"padding-top: 0;\">\n" +
            "            <div class=\"readyimg\" style=\"height:450px;background-color: rgb(247, 247, 247);box-shadow: 0px 0px 4px 0px rgb(201 201 201);\">\n" +
            "                <img src=\"\" >\n" +
            "            </div>\n" +
            "        </div>\n" +
            "        <div class=\"layui-col-xs3\">\n" +
            "           <div class=\"layui-row layui-col-space15\">\n" +
            "               <div class=\"layui-col-md12 img-preview\" style=\"width:200px;height:200px;overflow:hidden;border-radius: 5px;box-shadow: 0px 0px 4px 0px rgb(201 201 201);\">\n" +
            "               </div>\n" +
            "               <div class=\"layui-col-md12 img-preview\" style=\"width:200px;height:200px;padding:0px;border-radius:50%;margin-top:30px;overflow:hidden;box-shadow: 0px 0px 4px 0px rgb(201 201 201);\">\n" +
            "               </div>\n" +
            "           </div>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "    <div class=\"layui-row layui-col-space15\">\n" +
            "        <div class=\"layui-col-xs9\">\n" +
            "            <div class=\"layui-row\">\n" +
            "                <div class=\"layui-col-xs6\">\n" +
            "                    <button type=\"button\" class=\"layui-btn layui-icon layui-icon-left\" cropper-event=\"rotate\" data-option=\"-15\" title=\"Rotate -90 degrees\"> 向左旋转</button>\n" +
            "                    <button type=\"button\" class=\"layui-btn layui-icon layui-icon-right\" cropper-event=\"rotate\" data-option=\"15\" title=\"Rotate 90 degrees\"> 向右旋转</button>\n" +
            "                </div>\n" +
            "                <div class=\"layui-col-xs6\" style=\"text-align: right;\">\n" +
            "                    <button type=\"button\" class=\"layui-btn layui-icon layui-icon-refresh\" cropper-event=\"reset\" title=\"重置图片\">&nbsp;复位</button>\n" +
            "                </div>\n" +
            "            </div>\n" +
            "        </div>\n" +
            "        <div class=\"layui-col-xs3\">\n" +
            "            <button class=\"layui-btn layui-btn-fluid\" cropper-event=\"confirmSave\" type=\"button\"> 确定</button>\n" +
            "        </div>\n" +
            "    </div>\n" +
            "\n" +
            "</div>";
        var kaCroppers = {
            render: function (e) {
                $('body').append(html);
                var self = this,
                    elem = e.elem,
                    saveW = e.saveW,
                    saveH = e.saveH,
                    mark = e.mark,
                    area = e.area,
                    url = e.url,
                    returnType = e.returnType,
                    done = e.done;
                var content = $('.showImgEdit')
                    , image = $(".showImgEdit .readyimg img")
                    , preview = '.showImgEdit .img-preview'
                    , file = $(".showImgEdit input[name='file']")
                    , options = { aspectRatio: mark, preview: preview, viewMode: 1 };
                $(elem).on('click', function () {
                    layer.open({
                        title: "裁剪头像"
                        , type: 1
                        , content: content
                        , area: area
                        , shade: [0.6, '#FFF']
                        , success: function () {
                            image.cropper(options);
                        }
                        , cancel: function (index) {
                            layer.close(index);
                            image.cropper('destroy');
                        }
                    });
                });
                function convertBlobToBase64(blob) {
                    return new Promise((resolve, reject) => {
                        let reader = new FileReader();
                        reader.onloadend = () => {
                            resolve(reader.result);
                        };
                        reader.onerror = reject;
                        reader.readAsDataURL(blob);
                    });
                }
                $(".layui-btn").on('click', function () {
                    var event = $(this).attr("cropper-event");
                    //监听确认保存图像
                    if (event === 'confirmSave') {
                        image.cropper("getCroppedCanvas", {
                            width: saveW,
                            height: saveH
                        }).toBlob(function (blob) {
                            if(returnType == undefined){
                                var formData = new FormData();
                                formData.append('file', blob, 'head.jpg');
                                $.ajax({
                                    method: "post",
                                    url: url, //用于文件上传的服务器端请求地址
                                    data: formData,
                                    processData: false,
                                    contentType: false,
                                    success: function (result) {
                                        var res = eval('(' + result + ')');
                                        if (res.code == 0) {
                                            layer.msg("上传成功！");
                                            layer.closeAll('page');
                                            return 
                                        } else if (res.code == -1) {
                                            layer.alert(result.msg, { icon: 2 });
                                        }
                                        done(res.msg);
                                    }
                                });
                            } else if(returnType == "base64") {
                                convertBlobToBase64(blob).then(base64String => {
                                    done(base64String);
                                }).catch(error => {
                                    console.error(error);
                                }); 
                            }
                        });
                        //监听旋转
                    } else if (event === 'rotate') {
                        var option = $(this).attr('data-option');
                        image.cropper('rotate', option);
                        //重设图片
                    } else if (event === 'reset') {
                        image.cropper('reset');
                    }
                    //文件选择
                    file.change(function () {
                        var r = new FileReader();
                        var f = this.files[0];
                        r.readAsDataURL(f);
                        r.onload = function (e) {
                            image.cropper('destroy').attr('src', this.result).cropper(options);
                        };
                    });
                });
            }
        };
        exports('kaCroppers', kaCroppers);
    }
)